import multiprocessing
import threading

import time
from multiprocessing import Process, Manager, RLock

"""
变更共用，文件共读，且没锁机制的情况，就会出现数据混乱

def f(d):
    with lock:
        d["num"] += 1


if __name__ == '__main__':
    multiprocessing.set_start_method("fork")
    lock = RLock()
    with Manager() as manager:
        d = manager.dict()
        d["num"] = 0
        processes = []
        for i in range(20):
            p = Process(target=f, args=(d,))
            processes.append(p)
            p.start()
        for p in processes:
            p.join()
        print(d)
"""
"""
进程lock，可以做为参数传递,
spawn模式下，线程lock，不可以做为参数传递，会报错；fork可以，但线程lock只能干预同一进程下的线程
"""


def f(d, l):
    with l:
        d["num"] += 1


if __name__ == '__main__':
    multiprocessing.set_start_method("fork")
    lock = threading.Lock()
    with Manager() as manager:
        d = manager.dict()
        d["num"] = 0
        processes = []
        for i in range(20):
            p = Process(target=f, args=(d, lock))
            processes.append(p)
            p.start()
        for p in processes:
            p.join()    # spawn模式, join是必须，否则可能异常；fork是看情况，不是必须
        print(d)